package br.com.management.mentor.app.components.messageextractors;

import java.util.Locale;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import br.com.management.mentor.app.components.ExceptionMessageExtractor;

@Component
public class ConstraintViolationExceptionMessageExtractor implements ExceptionMessageExtractor {

	@Autowired
	private Locale locale;
	
	@Autowired
	private ApplicationContext context;
	
	@Override
	public boolean canHandle( Exception e ) {
		return e instanceof ConstraintViolationException;
	}

	@Override
	public String getMessage( Exception e ) {
		ConstraintViolationException cve = (ConstraintViolationException) e;
		
		StringBuilder message = new StringBuilder();
		
		for ( ConstraintViolation<?> constraint : cve.getConstraintViolations() ) {
			String fieldPath = String.format( "%s.%s" , constraint.getRootBeanClass().getSimpleName().toLowerCase() , constraint.getPropertyPath() );
			String field = context.getMessage( fieldPath , null , locale );
			
			if( message.length() > 0 ) message.append( "\n" );
			message.append( String.format( "%s - %s", field , constraint.getMessage() ) );
		}

		return message.toString();
	}
	
}